﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using uk.ac.soton.ses.DAL;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using uk.ac.soton.ses.UserControls;

namespace uk.ac.soton.ses.layouts
{
    public partial class CollectionDetails : LayoutsPageBase
    {
        private int _collectionID = -1;
        bool _isInitialised = false;
        MaterialsMetadataContext _dbcontext = null;
        ExperimentQuickSearch _experimentSearch = null;
        ExperimentCollection _experimentCollection = null;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this._dbcontext = HttpContext.Current.GetMaterialsDBContext();

            string idString = Page.Request.QueryString["CollectionID"];
            if (int.TryParse(idString, out this._collectionID))
            {
                this.LoadCollection();
                this.AddControls();
                this.ConfigureEvents();
                this._isInitialised = true;
            }
        }

        private void LoadCollection()
        {
            this._experimentCollection = this._dbcontext.GetExperimentCollectionByID(this._collectionID);
        }

        /// <summary>
        /// Add controls, scripts and style sheets dynamically not already in markup
        /// </summary>
        private void AddControls()
        {
            //Add stylesheet and javascript controls
            this.Page.AddHDCStylesheet();
            this.Page.AddHDCJQuery(true);
            this.Page.AddHDCJavaScript();
            this._experimentSearch = this.Control_ExperimentQuickSearch_Link as ExperimentQuickSearch;
        }

        /// <summary>
        /// Setup the event handlers for controls on the page
        /// </summary>
        private void ConfigureEvents()
        {
            this.View_Experiments.RowDataBound += new System.Web.UI.WebControls.GridViewRowEventHandler(View_Experiments_RowDataBound);
            this.View_Experiments.RowDeleting += new System.Web.UI.WebControls.GridViewDeleteEventHandler(View_Experiments_RowDeleting);

            this._experimentSearch.ExperimentSelected += new ExperimentSelectedEventHandler(AddExperimentToCollection);
        }

        private void View_Experiments_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
        {
            SPGridView gv = sender as SPGridView;
            if (gv != null)
            {
                //Find out which experiment is being removed from container
                int experimentIDDeleting = (int)gv.DataKeys[e.RowIndex]["ID"];

                //Perform the deletion
                this._dbcontext.DeleteExperimentFromCollection(this._collectionID, experimentIDDeleting, true);

                //Rebind the grid view
                this.DataBindExperimentGrid();
            }
        }

        private void View_Experiments_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            SPGridViewRow gvr = e.Row as SPGridViewRow;

            //Check we have a row, otherwise don't bind anything
            if (gvr == null)
            {
                return;
            }

            //Get the experiment and the link control we need to modify
            Experiment linkedExperiment = gvr.DataItem as Experiment;
            HyperLink experimentLink = gvr.FindControl("link_ExperimentDetails") as HyperLink;

            //Check we have a control before binding anything
            if (experimentLink != null && linkedExperiment != null)
            {
                experimentLink.NavigateUrl = HDCConfiguration.GetUrl_ExperimentDetails(linkedExperiment.ID);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this._isInitialised)
            {
                if (this._collectionID > 0 && !Page.IsPostBack)
                {
                    //Add a heading
                    this.literal_CollectionTitle.Text = string.Format("<h3 class=\"HDCH3\">Collection {0}&mdash;&quot;{1}&quot;</h3>", this._experimentCollection.ID, this._experimentCollection.Name);

                    //Set page title (SharePoint friendly)
                    this.literal_PageTitle.Text = string.Format("Collection {0}&mdash;&quot;{1}&quot;", this._experimentCollection.ID, this._experimentCollection.Name);

                    this.DataBindExperimentGrid();
                }
            }
        }

        private void DataBindExperimentGrid()
        {
            IQueryable<Experiment> experimentsMapped = this._dbcontext.GetExperimentsByCollectionID(this._collectionID, true);
            View_Experiments.DataSource = experimentsMapped;
            View_Experiments.DataBind();
        }

        private void AddExperimentToCollection(object sender, ExperimentSelectedEventArgs e)
        {
            this._dbcontext.AddExperimentToCollection(this._collectionID, e.SelectedExperimentID, true);

            this.DataBindExperimentGrid();
        }

    }
}
